﻿#region Usings

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using Gonte.Wpf.Controls.ViewModel;

#endregion

namespace Gonte.Wpf.Controls.UserControls
{
    public partial class TreeViewUserControl
        : UserControl
    {
        public TreeViewUserControl()
        {
            InitializeComponent();
        }

        public ItemViewModel ViewModel
        {
            get { return (ItemViewModel)treeView.DataContext; }

            set { treeView.DataContext = value; }
        }

        public TreeView TreeView
        {
            get { return treeView; }
        }

        #region Event handlers

        /// <summary>
        /// Fires an event of the view model when the tree changes the selection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeView selected = (TreeView)e.OriginalSource;
            ItemViewModel viewModel = selected.SelectedValue as ItemViewModel;

            viewModel.OnSelectionChanged(sender, viewModel);

            ContextMenu = viewModel.CreateContextMenu();
        }

        /// <summary>
        /// Selects the item when it is right clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTreeViewItemMouseRightButtonDown(object sender, MouseEventArgs e)
        {
            TreeViewItem item = sender as TreeViewItem;
            if (item != null)
            {
                item.Focus();
                e.Handled = true;
            }
        }

        #endregion
    }
}
